package com.zjhome.itoken.web.admin.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zjhome.itoken.common.domain.TbSysUser;
import com.zjhome.itoken.common.utils.CookieUtils;
import com.zjhome.itoken.common.utils.MapperUtils;
import com.zjhome.itoken.web.admin.service.RedisService;

public class WebAdminInterceptor implements HandlerInterceptor {
	@Autowired
	private RedisService 	redisService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 

		String token = CookieUtils.getCookieValue(request, "token");
		if (StringUtils.isBlank(token)) {
			// 验证登陆失败，跳到单点登陆页面
			response.sendRedirect("http://localhost:8503/login?url=http://localhost:8601");
			return false;
		}
		
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//		
		TbSysUser tbSysUser = (TbSysUser)request.getSession().getAttribute("loginUser");
		if (tbSysUser != null) {
			// 已经登陆
			if (modelAndView != null) {
				modelAndView.addObject("loginUser", tbSysUser);
			}
		}
		else {
			// 未登陆
			String token = CookieUtils.getCookieValue(request, "token");
			if (StringUtils.isNotBlank(token)) {
				String user = redisService.get(token);
				if (StringUtils.isNotBlank(user)) {	
					String json = redisService.get(user);
					if (StringUtils.isNotBlank(json)) {
						
						tbSysUser = MapperUtils.json2pojo(json, TbSysUser.class);
						if (tbSysUser != null) {
							// 创建局部会话
							if (modelAndView != null) {
								modelAndView.addObject("loginUser", tbSysUser);
							}
							request.getSession().setAttribute("loginUser", tbSysUser);
						}
					}
				}
			}
		}
		
		if (tbSysUser == null) {
			// 跳转到登陆页面
			response.sendRedirect("http://localhost:8503/login?url=http://localhost:8601");
		}		
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
